<?php

namespace plugin\admin\app\model;

use support\exception\BusinessException;
use think\facade\Validate;
use think\Model;


class BaseThink extends Model
{
    // 定义时间戳字段名
    protected $connection = 'plugin.admin.mysql';
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';
    protected $autoWriteTimestamp = 'datetime';

    public static function onBeforeWrite($model)
    {
        // 关联自动验证规则，实现自动验证
        try {
            if(isset($model->validate)){
                $ruleData = $model->validate;
                $validateObj = Validate::rule($ruleData['rule']);
                $validateObj->message($ruleData['msg'])->batch(true)->failException(true)->check($model->getData());
            }
        } catch (\Throwable $exception) {
            // 验证失败 输出错误信息
            throw new BusinessException($exception->getMessage() ?: '表名不合法');
        }
    }
}
